package handler

import (
	"day1028/cache"
	"day1028/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	data := model.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "article_" + title
	model.DB.Create(&data)
	jsonData, _ := json.Marshal(&data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var data model.Article
	model.DB.Where("id = ?", id).Limit(1).Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
func Delete(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	var data model.Article
	model.DB.Where("id = ?", id).Delete(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var data []model.Article
	redis_key := "article_all"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Limit(1).Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
